import jsonp from 'jsonp'
import JsBridge from '@/utils/jsBridge'
import store from '@/store'
import { NATIVE_TYPE, Position } from '@/type'

export const deepClone = (obj: any) => {
  if (typeof obj !== 'object' || obj == null) {
    return obj
  }
  let result: any
  if (obj instanceof Array) {
    result = []
  } else {
    result = {}
  }
  for (const key in obj) {
    // eslint-disable-next-line no-prototype-builtins
    if (obj.hasOwnProperty(key)) {
      result[key] = deepClone(obj[key])
    }
  }
  return result
}

export const debounce = (fn: () => void, debounceTime = 300) => {
  let timer: any
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      console.log(debounceTime)
      fn()
      clearTimeout(timer)
    }, debounceTime)
  }
}

//获取当前定位
export const location = (isJustH5Location = false) => {
  return new Promise<Position>((resolve, reject) => {
    if (isApp() && !isJustH5Location) {
      JsBridge.jsCallNative(NATIVE_TYPE.GET_CURRENT_POSITION, {})
    } else {
      const geolocation = new BMapGL.Geolocation()
      geolocation.enableSDKLocation()
      geolocation.getCurrentPosition(function (r: any) {
        const position: Position = {
          longitude: '',
          latitude: '',
          status: geolocation.getStatus()
        }
        if (geolocation.getStatus() == 0) {
          position.longitude = r.longitude
          position.latitude = r.latitude
          store.commit('system/setCurrentPosition', JSON.stringify(position))
        }
        resolve(position)
      })
    }
  })
}

// //获取当前定位
// export const location = () => {
//   if (isApp()) {
//     JsBridge.jsCallNative(NATIVE_TYPE.GET_CURRENT_POSITION, {})
//   } else {
//     const geolocation = new BMap.Geolocation()
//     geolocation.enableSDKLocation()
//     geolocation.getCurrentPosition(function (r: any) {
//       if (geolocation.getStatus() == 0) {
//         store.commit('system/setCurrentPosition', JSON.stringify({ longitude: r.longitude, latitude: r.latitude }))
//         store.commit('system/setPositionFlag', 2)
//       } else {
//         store.commit('system/setPositionFlag', 3)
//       }
//     })
//   }
// }

// 判断是否在app内部打开
export const isApp = (): boolean => {
  if (navigator.userAgent.indexOf('Android_Web') != -1 || navigator.userAgent.indexOf('IOS_Web') != -1) {
    return true
  }
  return false
}
